package com.ebelter.myehc.ui.activitys;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.BaseResponse;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.WheelView;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.btcomlib.views.dialogs.WheelViewDialog;
import com.ebelter.btcomlib.views.dialogs.picktime2.CustomDatePicker;
import com.ebelter.myehc.R;
import com.ebelter.myehc.models.http.request.EhcNetUtils;
import com.ebelter.myehc.models.http.response.device_resports.BC_R;
import com.ebelter.myehc.models.http.response.device_resports.BG_R;
import com.ebelter.myehc.models.http.response.device_resports.BO_R;
import com.ebelter.myehc.models.http.response.device_resports.BP_R;
import com.ebelter.myehc.models.http.response.device_resports.Cholesterol_R;
import com.ebelter.myehc.models.http.response.device_resports.Temperature_R;
import com.ebelter.myehc.models.http.response.device_resports.Ua_R;
import com.ebelter.myehc.ui.fragments.trends.Trend_Bra_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_NiaoSuan_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_Scale_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_TiWen_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_XueTang_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_XueYa_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_XueYang_Fragment;
import com.ebelter.myehc.ui.fragments.trends.Trend_ZDGCH_Fragment;
import com.ebelter.myehc.ui.view.CombinView9;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import static com.ebelter.btcomlib.views.dialogs.TextTipDialog.Gravity_BUTTOM;

public class TrendActivity extends EhcBaseActivity implements View.OnClickListener {

    public static final String TAG = "TrendActivity";
    public static final String KEY = "TrendActivity_KEY";
    public static final int Trend_XUEYA = 1;//血压
    public static final int Trend_XUEYANG = 2;//血氧
    public static final int Trend_TIWEN = 3;//体温
    public static final int Trend_XUETANG = 4;//血糖
    public static final int Trend_NIAOSUAN = 5;//尿酸
    public static final int Trend_ZONGDANGUCHUN = 6;//总胆固醇
    public static final int Trend_TIZHICHENG = 7;//体脂秤
    public static final int Trend_BRA = 8;//手环 锻炼




    //1:血糖 2:血压 3:血氧 4:体温 5:尿酸 6:总胆固醇 7:人体成份 8手环
    private int getRequestMeasureTypeByCurrentModifyType(){
        if (currentModifyType==Trend_XUEYA){
            return 2;
        }else if (currentModifyType==Trend_XUEYANG){
            return 3;
        }else if (currentModifyType==Trend_TIWEN){
            return 4;
        }else if (currentModifyType==Trend_XUETANG){
            return 1;
        }else if (currentModifyType==Trend_NIAOSUAN){
            return 5;
        }else if (currentModifyType==Trend_ZONGDANGUCHUN){
            return 6;
        }else if (currentModifyType==Trend_TIZHICHENG){
            return 7;
        }else if (currentModifyType==Trend_BRA){
            return 8;
        }
        return -1;
    }



    public int currentModifyType;


    private ImageView top_left_iv;
    private TextView top_title_tv;
    private ImageView top_right_iv;


    private CombinView9 leftTimeCb9;
    private CombinView9 rightTime1_Cb9;
    private CombinView9 rightTime2_Cb9;

    private TextView zi_tv;//自
    private TextView zhi_tv;//至


    private int leftType = 0;//0天1周2月3年

    //dateType  1:年 2:月 3周: 4:天
    //leftType 0天1周2月3年
    private int getDateTypeByLeftType(){
        if (leftType==0){
            return 4;
        }else if (leftType==1){
            return 3;
        }else if (leftType==2){
            return 2;
        }else if (leftType==3){
            return 1;
        }
        return -1;
    }

    private int tzhyn_selectedIndex = 1;


    private long time1;
    private long time2;


    private Fragment currentFragment;


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_trend;
    }


    @Override
    protected void initView() {
        super.initView();
        currentModifyType = getIntent().getIntExtra(KEY,-1);
        if (currentModifyType==-1){
            throw new RuntimeException("参数不对异常");
        }
        EventBus.getDefault().register(this);

        FV();
        setListener();
        currentFragment=getFragmentByType();
        replaceFragment(currentFragment,R.id.trend_contain_f);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommonEventBus event) {
        if (!TextUtils.equals(event.whichReceive,TAG)){
            return;
        }
        LogUtils.i(TAG,"TrendActivity--onEventMainThread接收到CommonEventBus信息--"+event.toString());
        if (TextUtils.equals(event.from,Trend_Bra_Fragment.TAG)){//说明来自Trend_Bra_Fragment消息
            int pageSelect = event.cmd;  //0说明是锻炼趋势 1心率趋势 2睡眠趋势
            if (pageSelect==1||pageSelect==2){
                //判断//leftType 0天1周2月3年
                if (leftType==2||leftType==3){
                    leftType=0;
                    updateRightTime1();
                    updateRightTime2();
                    updateTopTimeLayout();
                }

            }
            getReportData();
        }



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setListener() {
        top_left_iv.setOnClickListener(this);
        top_right_iv.setOnClickListener(this);

        leftTimeCb9.setOnClickListener(this);
        rightTime1_Cb9.setOnClickListener(this);
        rightTime2_Cb9.setOnClickListener(this);

    }

    private void FV() {
        top_left_iv=findViewById(R.id.top_left_iv);
        top_right_iv=findViewById(R.id.top_right_iv);
        top_title_tv=findViewById(R.id.m_title_tv);

        leftTimeCb9=findViewById(R.id.topTime_lefttype_cb9);
        rightTime1_Cb9=findViewById(R.id.topTime_right1_cb9);
        rightTime2_Cb9=findViewById(R.id.topTime_right2_cb9);
        zi_tv=findViewById(R.id.topTime_zi_tv);
        zhi_tv=findViewById(R.id.topTime_zhi_tv);
    }





    @Override
    protected void initData() {
        super.initData();


        time1 = System.currentTimeMillis();
        time2 = System.currentTimeMillis();

        updateRightTime1();
        updateRightTime2();
        updateTopTimeLayout();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getReportData();
    }

    //更新时间1
    private void updateRightTime1(){
        if (rightTime1_Cb9!=null) {
            rightTime1_Cb9.setTitle1(getDisplayTimeByLeftType(time1,leftType));
        }
    }
    //更新时间2
    private void updateRightTime2(){
        if (rightTime2_Cb9!=null){
            rightTime2_Cb9.setTitle1(getDisplayTimeByLeftType(time2,leftType));
        }
    }

    /**
     * @param leftType 0天1周2月3年
     */
    private String getDisplayTimeByLeftType(long time,int leftType){

        if (leftType==0||leftType==1){
            return getDisTime(0,time);//"yyyy-M-d"
        }else if (leftType==2){
            return getDisTime(1,time);//"yyyy-M-d"
        }else {
            return TimeUtils.formatTime10(time);// "yyyy"
        }


    }
    //yyyy-MM-dd HH:mm:ss:SSS
    //type 0年月日 1年月 2年
    public static String getDisTime(int type,long time){
        String format="";
        String country = AppUtils.getLocalStr();
        if (TextUtils.equals(country, AppUtils.en)){//除了英文其他一律显示中文的

            if (type==0){
                format="M/d/yy";
            }else if (type==1){
                format="M/yy";
            }else if (type==2){
                format="yy";
            }

        }else {

            if (type==0){
                format="yyyy/M/d";
            }else if (type==1){
                format="yyyy/M";
            }else if (type==2){
                format="yyyy";
            }
        }

        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat=new SimpleDateFormat(format);
        return TimeUtils.formatTimeByMyselt(simpleDateFormat,time);
    }




    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id==R.id.top_left_iv){
            finish();
        }else if (id==R.id.top_right_iv){

            Intent intent = new Intent(this,HistoryActivity.class);
            int modify = currentModifyType;

            intent.putExtra(HistoryActivity.KEY,modify);
            startActivity(intent);

        }else if (id==R.id.topTime_lefttype_cb9){
            showTZHYNDialog();
        }else if (id==R.id.topTime_right1_cb9){
            showTimeSelectDialog1();
        }
    }


    //弹出时间选择器
    private void showTimeSelectDialog1() {

        rightTime1_Cb9.setImage1(R.drawable.ic_shangla);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String time = sdf.format(time1);
        String endTime = sdf.format(Calendar.getInstance().getTime().getTime());
        String date = time.split(" ")[0];
        CustomDatePicker datePicker= new CustomDatePicker(this,new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                LogUtils.i(TAG,time);
                time1 = TimeUtils.parseFormatter6Time(time).getTime();

                if (leftType==1){//如果此时是周

                    long t2=time1+6*24*3600000;//time1一周以后的时间
                    if (t2>System.currentTimeMillis()){
                        t2=System.currentTimeMillis();
                    }
                    time2=t2;

                }

                updateRightTime1();
                updateRightTime2();

                getReportData();


            }
        }, "1945-01-01 00:00", endTime);
        // datePicker.setSelectedCalender("1991-06-13");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);

        datePicker.show(date);
        datePicker.setShowTime(leftType);
        datePicker.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (rightTime1_Cb9!=null){
                    rightTime1_Cb9.setImage1(R.drawable.ic_xiala);
                }
            }
        });
        datePicker.setBackgroundColor(getResources().getColor(R.color.redTheme));

    }

    //展示天周月年对话框
    private void showTZHYNDialog() {
        if (leftTimeCb9!=null)leftTimeCb9.setImage1(R.drawable.ic_shangla);

        WheelViewDialog wheelViewDialog = new WheelViewDialog(this);
        wheelViewDialog.setGravity(Gravity_BUTTOM);


        List<String> list=new ArrayList<>();

            list.add(getString_(R.string.tian));
            list.add(getString_(R.string.zhou));
        if (currentModifyType==Trend_BRA&&currentFragment instanceof Trend_Bra_Fragment){
            int pageSelect = ((Trend_Bra_Fragment)currentFragment).getPageSelectedPosition();
            if (pageSelect==0){
                list.add(getString_(R.string.yue));
                list.add(getString_(R.string.nian));
            }
        }else {
            list.add(getString_(R.string.yue));
            list.add(getString_(R.string.nian));
        }

        wheelViewDialog.setOffeset(1);
        wheelViewDialog.setItems(list);
        wheelViewDialog.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                Log.i(TAG, "selectedIndex: " + selectedIndex + ", item: " + item);
                tzhyn_selectedIndex = selectedIndex;
            }
        });
        wheelViewDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                Log.i(TAG, "cancel");
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                Log.i(TAG, "ok");
                dialogView.cancel();
                int newType = tzhyn_selectedIndex-1;
                if (newType!=leftType){
                    leftType=newType;

                    if (leftType==1){//0天1周2月3年
                        //说明选到周了
                        long cT=System.currentTimeMillis();//当前时间
                        if (cT-time1<24*3600000*6){
                            //说明time1在7天时间内 所以
                            time1=cT-24*3600000*6;
                        }
                        time2=time1+24*3600000*6;

                    }

                    updateTopTimeLayout();
                    updateRightTime1();
                    updateRightTime2();
                    getReportData();
                }

            }
        });

        wheelViewDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (leftTimeCb9!=null) leftTimeCb9.setImage1(R.drawable.ic_xiala);
            }
        });

        wheelViewDialog.setSelectPosition(leftType);

        wheelViewDialog.show();



    }

    //更新顶部的时间布局
    private void updateTopTimeLayout() {
        if (leftType==0){
            setCb9Value(leftTimeCb9,getString_(R.string.tian));
        }else if (leftType==1){
            setCb9Value(leftTimeCb9,getString_(R.string.zhou));
        }else if (leftType==2){
            setCb9Value(leftTimeCb9,getString_(R.string.yue));
        }else if (leftType==3){
            setCb9Value(leftTimeCb9,getString_(R.string.nian));
        }
        setRightTimeLayout(leftType);

    }

    private void setCb9Value(CombinView9 cb9,String value){
        if (cb9!=null) cb9.setTitle1(value);
    }


    private void setRightTimeLayout(int leftType){
        if (leftType==0||leftType==2||leftType==3){
            ViewUtils.goneView(zi_tv);
            ViewUtils.goneView(zhi_tv);
            ViewUtils.goneView(rightTime2_Cb9);
        }else if (leftType==1){
            ViewUtils.displayView(zi_tv);
            ViewUtils.displayView(zhi_tv);
            ViewUtils.displayView(rightTime2_Cb9);
        }
    }



    private void getReportData(){
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        //获取设备报表数据
        //measureType  1:血糖 2:血压 3:血氧 4:体温 5:尿酸 6:总胆固醇 7:人体成份
        //dateType  1:年 2:月 3周: 4:天
        //param  参数值 年：2018  月2018-01 周 2018-01-01（转开始日期就行，后台自动T+7） 天 2018-01-02
        String authKey = MainActivity.getAuthKey();

       int measureType = getRequestMeasureTypeByCurrentModifyType(); //请求的数据类型

        if (measureType == 8){ //如果是手环参数 底下有锻炼 心率和睡眠之分
            //8:锻炼 9:心率 10:睡眠
            //说明是手环界面
            int selectPosition = ((Trend_Bra_Fragment)currentFragment).getPageSelectedPosition();
            if (selectPosition==0){
                measureType=8;
            }else if (selectPosition==1){
                measureType=9;
            }else if (selectPosition==2){
                measureType=10;
            }

        }
        final int finalMeasureType = measureType;

        final int dateType = getDateTypeByLeftType();

        final String param = getTimeParamByDateType(dateType);


        EhcNetUtils.getInstance().cancelTag(this);
        EhcNetUtils.getInstance().getDeviceReportData(this, authKey, finalMeasureType, dateType, param, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                LogUtils.i(TAG,"--measureType = "+ finalMeasureType +"--dateType = "+dateType+"----param = "+param);
                LogUtils.i(TAG,"---------------------------------------------------------------------\n"+s);

                if (isRequestSuccess&&baseResponse!=null&&baseResponse.resultCode==1){
                    dealReportData(finalMeasureType,baseResponse);//说明请求数据成功
                }else {
                    ToastUtil.show(R.string.Server_unresponsive_please_try_again_later);
                }

            }
        });


    }


    //处理请求的报表数据
    //measureType  1:血糖 2:血压 3:血氧 4:体温 5:尿酸 6:总胆固醇 7:人体成份 8手环 锻炼  9心率 10睡眠
    //dateType  1:年 2:月 3周: 4:天
    private void dealReportData(int measureType, BaseResponse baseResponse) {
        if (measureType==1){//血糖
            ((Trend_XueTang_Fragment)currentFragment).setReportData((BG_R)baseResponse);
        }else if (measureType==2){//血压 ok
            ((Trend_XueYa_Fragment)currentFragment).setReportData((BP_R)baseResponse);
        }else if (measureType==3){//血氧
            ((Trend_XueYang_Fragment)currentFragment).setReportData((BO_R)baseResponse);
        }else if (measureType==4){//体温
            ((Trend_TiWen_Fragment)currentFragment).setReportData((Temperature_R)baseResponse);
        }else if (measureType==5){//尿酸
            ((Trend_NiaoSuan_Fragment)currentFragment).setReportData((Ua_R) baseResponse);
        }else if (measureType==6){//总胆固醇
            ((Trend_ZDGCH_Fragment)currentFragment).setReportData((Cholesterol_R)baseResponse);
        }else if (measureType==7){//人体成份
            ((Trend_Scale_Fragment)currentFragment).setReportData((BC_R)baseResponse);
        }else if (measureType==8||measureType==9||measureType==10){
            ((Trend_Bra_Fragment)currentFragment).setReportData(measureType,baseResponse);
        }

    }


    public Fragment getFragmentByType(){
        Fragment fragment = null;
        String title = "";
        if (currentModifyType==Trend_XUEYA){
            fragment=new Trend_XueYa_Fragment();
            title=getString_(R.string.xyqsh);
        } else if (currentModifyType==Trend_XUEYANG){
            title=getString_(R.string.xybhdqsh);
            fragment=new Trend_XueYang_Fragment();
        }else if (currentModifyType==Trend_TIWEN){
            title=getString_(R.string.twqsh);
            fragment=new Trend_TiWen_Fragment();
        }else if (currentModifyType==Trend_XUETANG){
            title=getString_(R.string.xtqsh);
            fragment=new Trend_XueTang_Fragment();
        }else if (currentModifyType==Trend_NIAOSUAN){
            title=getString_(R.string.nsqsh);
            fragment=new Trend_NiaoSuan_Fragment();
        }else if (currentModifyType==Trend_ZONGDANGUCHUN){
            title=getString_(R.string.zdgchqsh);
            fragment=new Trend_ZDGCH_Fragment();
        }else if (currentModifyType==Trend_TIZHICHENG){
            title=getString_(R.string.tzhchqsh);
            fragment=new Trend_Scale_Fragment();
        }else if (currentModifyType==Trend_BRA){
            title=getString_(R.string.dlqsh);
            Trend_Bra_Fragment fragment2=new Trend_Bra_Fragment();
            fragment2.setTop_title_tv(top_title_tv);
            fragment=fragment2;
        }
        top_title_tv.setText(title);
        return fragment;
    }


    //dateType  1:年 2:月 3周: 4:天
    //param  参数值 年：2018  月2018-01 周 2018-01-01（转开始日期就行，后台自动T+7） 天 2018-01-02
    private String getTimeParamByDateType(int dateType) {
        String timeParam;
        if (dateType==1){
            timeParam = TimeUtils.formatTime10(time1);//yyyy
        }else if (dateType==2){
            timeParam = TimeUtils.formatTime91(time1);//yyyy-MM
        }else if (dateType==3){
            timeParam = TimeUtils.formatTime3(time1);//yyyy-MM-dd
        }else if (dateType==4){
            timeParam = TimeUtils.formatTime3(time1);//yyyy-MM-dd
        }else {
            LogUtils.i(TAG,"-------dateType = "+dateType);
            throw new IllegalArgumentException("非法参数异常");
        }
        return timeParam;
    }
}
